﻿package app.view.components.guiDima.slideShowD
{
	import app.view.events.ImageEvent;
	import flash.display.Bitmap;
	import flash.display.Loader;
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.geom.Rectangle;
	import flash.net.URLRequest;
	import flash.utils.setTimeout;
	import gs.TweenLite;
	
	/**
	 * Универсальная штука для загрузки фото
	 * @author Dmitryi_Koruagin, icq:585466579, dmitryikoruagin@yandex.ru
	 */
	public class Image extends Sprite
	{
		
		private var _w:Number;
		private var _h:Number;
		private var _cont:Shape;
		private var _url:String;
		private var _loader:Loader;
		private var _isLoad:Boolean=false;
		private var _isLoading:Boolean=false;
		private var _isShow:Boolean;
		private var _resizePolicy:String;
		private var _alignPolicy:String;
		//	const
		public static const RESIZE_NONE:String = 'resize_none';
		public static const RESIZE_MAX:String = 'resize_max';
		public static const RESIZE_MIN:String = 'resize_min';
		public static const RESIZE_WIDTH:String = 'resize_width';
		public static const RESIZE_HEIGHT:String = 'resize_height';
		
		public static const ALIGN_NONE:String = 'align_none';
		public static const ALIGN_CENTER:String = 'align_center';
		public static const ALIGN_VERTICAL:String = 'align_vertical';
		public static const ALIGN_HORIZONTAL:String = 'align_horizontal';
		
		private var _currentWidth:Number;
		private var _currentHeight:Number;
		private var _bgdalpha:Number=1;
		private var _timeShow:Number=0.5;
		private var _bgdColor:uint=0xff0000;
		private var _isPreloader:Boolean;
		private var _preloader:Preloader;
		private var _preloaderwidth:Number;
		private var _isFree:Boolean = false;
		private var _isBitmap:Boolean;
		// для рамки -)
		private var _isborder:Boolean;
		private var _borderWidth:Number = 1;
		private var _borderColor:Number = 0xffffff;
		private var _border:Shape;
		
		
		//	CONSTRUCTOR
		/**
		 * фотка
		 * @param	w - ширина компонента
		 * @param	h - высота компонента
		 * @param	resizePolicy - политика ресайза
		 * @param	bgdalpha - альфа фона
		 * @param	bgdColor - цвет фона
		 * @param	alignPolicy - политика выравнивания
		 * @param	isPreloader - прелоадер(вкл/выкл)
		 * @param	preloaderwidth - ширина прелоадера
		 */
		public function Image(w:Number,h:Number,resizePolicy:String=RESIZE_NONE,alignPolicy:String=ALIGN_NONE,bgdalpha:Number=0,bgdColor:uint=0xff0000,isPreloader:Boolean=false,preloaderwidth:Number=100,isBitmap:Boolean=true,isborder:Boolean=false) 
		{
			_w = w;
			_h = h;
			_resizePolicy = resizePolicy;
			_bgdalpha = bgdalpha;
			_bgdColor = bgdColor;
			_alignPolicy = alignPolicy;
			_isPreloader = isPreloader;
			_preloaderwidth = preloaderwidth;
			_isBitmap = isBitmap;
			_isborder = isborder;
			
			init();
		}
		
		//	METHODS
		
		//	private
		private function init():void
		{
			_cont = new Shape();
			_cont.alpha = 0;
			_cont.graphics.beginFill(_bgdColor,_bgdalpha);
			_cont.graphics.drawRect(0, 0, _w, _h);
			_cont.graphics.endFill();
			addChild(_cont);
			
			//this.alpha = 0;
			//this.mouseChildren = false;
			//this.mouseEnabled = false;
			
			// проверяем чтобы прелоадер не был больше шириной самой фотки
			_preloaderwidth > _w ? _preloaderwidth = _w : 0;
			
			_preloader = new Preloader(_preloaderwidth);
			_preloader.x = _cont.width / 2 - _preloader.width / 2;
			_preloader.y = _cont.height / 2 - _preloader.height / 2;
			_preloader.alpha = 0;
			addChild(_preloader);
			
			_loader = new Loader();
			_loader.alpha = 0;
			addChild(_loader);
			
			scrollRect = new Rectangle(0, 0, _w, _h);
		}
		
		private function showPreloader():void
		{
			if (_isLoading==true && _isLoad==false) 
			{
				TweenLite.to(_preloader, 0.3, { alpha: 1 , ease:'none' } );
			}
			
		}
		
		//	public
		public function clear():void
		{
			////trace('clear');
			if (_isLoading==true) 
			{
				_loader.contentLoaderInfo.removeEventListener(Event.INIT, onLoad);
				_loader.contentLoaderInfo.removeEventListener(ProgressEvent.PROGRESS, onProgress);
				_loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, onError);
				try 
				{
					_loader.close();
					_loader.unload();
				}catch (err:Error){}
			}
			_loader.alpha = 0;
		}
		
		public function destroy():void
		{
			if (_isLoading==true) 
			{
				_loader.removeEventListener(Event.INIT, onLoad);
				_loader.contentLoaderInfo.removeEventListener(ProgressEvent.PROGRESS, onProgress);
				_loader.removeEventListener(IOErrorEvent.IO_ERROR, onError);
				try 
				{
					_loader.close();
					_loader.unload();
					
					
				}catch (err:Error){}
				
			}
			try 
			{
				if (_isborder==true && _border) 
				{
					removeChild(_border);
				}
				
				removeChild(_border);
				_preloader.destroy();
				removeChild(_preloader);
				removeChild(_loader);
				removeChild(_cont);
			}catch (err:Error)
			{
				
			}
			
			
		}
		
		public function loadImage(url:String):void
		{
			////trace('loadImage',url);
			if (url!=null && url!='') 
			{
				_isShow = false;
				_isLoading = true;
				_loader.alpha = 0;
				_loader.contentLoaderInfo.addEventListener(Event.INIT, onLoad);
				_loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onError);
				_loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgress);
				_loader.load(new URLRequest(url));
				
				//setTimeout(dispatch, 200);
				if (_isPreloader==true) 
				{
					setTimeout(showPreloader, 600);
				}
			}
		}
		
		private function dispatch():void
		{
			var ev:ImageEvent = new ImageEvent(ImageEvent.IMAGE_LOAD);
			dispatchEvent(ev);
		}
		
		
		public function resetLoadImage():void
		{
			////trace('resetLoadImage');
			_isLoad = false;
			_isShow = false;
			_isLoading = false;
			TweenLite.to(_loader, 0.3, { alpha: 0 } );
			_preloader.resetProgress();
			
			if (_isborder==true && _border) 
			{
				removeChild(_border);
			}
			
			if (_isLoading==true || _isLoad==true) 
			{
				_loader.contentLoaderInfo.removeEventListener(Event.INIT, onLoad);
				_loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, onError);
				_loader.contentLoaderInfo.removeEventListener(ProgressEvent.PROGRESS, onProgress);
				try 
				{
					_loader.close();
					_loader.unload();
				}catch (err:Error){	}
				
			}
			
		}
		//	----------------------------------------------------------------------------------
		
		//	GETTERS/SETTERS
		
		//	----------------------------------------------------------------------------------
		
		//	HANDLERS
		private function onLoad(e:Event):void 
		{
			////trace('onLoad');
			_loader.contentLoaderInfo.removeEventListener(Event.INIT, onLoad);
			_loader.contentLoaderInfo.removeEventListener(ProgressEvent.PROGRESS, onProgress);
			_loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, onError);
			
			_isLoading = false;
			_isLoad = true;
			
			_preloader.resetProgress();
			
			TweenLite.to(_preloader, 0.3, { alpha: 0 , ease:'none' } );
			
			_isBitmap==true ? Bitmap(_loader.content).smoothing = true : 0;
			
			var scale:Number;
			switch (_resizePolicy) 
			{
				case RESIZE_NONE:
					scale = 1;
					_loader.scaleX = _loader.scaleY = scale;
				break;
				
				case RESIZE_MAX:
					scale = Math.max(_w / _loader.content.width, _h / _loader.content.height);
					_loader.scaleX = _loader.scaleY = scale;
				break;
				
				case RESIZE_MIN:
					scale = Math.min(_w / _loader.content.width, _h / _loader.content.height);
					_loader.scaleX = _loader.scaleY = scale;
				break;
				
				case RESIZE_WIDTH:
					scale = _w / _loader.content.width;
					_loader.scaleX = _loader.scaleY = scale;
				break;
				
				case RESIZE_HEIGHT:
					scale = _h / _loader.content.height;
					_loader.scaleX = _loader.scaleY = scale;
				break;
			}
			
			switch (_alignPolicy) 
			{
				case ALIGN_NONE:
					_loader.x = 0;
					_loader.y = 0;
				break;
				
				case ALIGN_CENTER:
					_loader.x = _w / 2 - _loader.width / 2;
					_loader.y = _h / 2 - _loader.height / 2;
					
				break;
				
				case ALIGN_HORIZONTAL:
					_loader.x = _w / 2 - _loader.width / 2;
				break;
				
				case ALIGN_VERTICAL:
					_loader.y = _h/ 2 - _loader.height / 2;
				break;
			}
			
			////trace('loader', _loader.height);
			_currentWidth = _loader.width;
			_currentHeight = _loader.height;
			
			if (_isborder==true) 
			{
				_border = new Shape();
				_border.alpha = 0;
				_border.graphics.lineStyle(_borderWidth, _borderColor,1,true);
				_border.graphics.drawRect(_loader.x, _loader.y, _loader.width, _loader.height);
				addChild(_border);
				TweenLite.to(_border, _timeShow, { alpha: 1} );
			}
			
			TweenLite.to(_loader, _timeShow, { alpha: 1, onComplete:onFinishShowImage } );
			
			////trace('scale',scale,_loader.x,_loader.y);
			
			var obj:Object = new Object();
			obj.cscale = scale;
			obj.cx = _loader.x;
			obj.cy = _loader.y;
			
			var ev:ImageEvent = new ImageEvent(ImageEvent.IMAGE_LOAD);
			ev.data = obj;
			dispatchEvent(ev);
		}
		
		private function onFinishShowImage():void
		{
			_isShow = true;
			var ev:ImageEvent = new ImageEvent(ImageEvent.IMAGE_SHOW);
			dispatchEvent(ev);
		}
		
		private function onError(e:IOErrorEvent):void 
		{
			//trace('e image load',e.text);
		}
		
		private function onProgress(e:ProgressEvent):void 
		{
			var pr:Number = e.bytesLoaded / e.bytesTotal * 100;
			pr = Math.round(pr);
			
			_preloader.progress = pr;
		}
		
		
		public function get isLoad():Boolean { return _isLoad; }
		
		public function set isLoad(value:Boolean):void 
		{
			_isLoad = value;
		}
		
		public function get isLoading():Boolean { return _isLoading; }
		
		public function set isLoading(value:Boolean):void 
		{
			_isLoading = value;
		}
		
		public function get isShow():Boolean { return _isShow; }
		
		public function set isShow(value:Boolean):void 
		{
			_isShow = value;
		}
		
		public function get currentWidth():Number { return _currentWidth; }
		
		public function get currentHeight():Number { return _currentHeight; }
		
		public function get timeShow():Number { return _timeShow; }
		
		public function set timeShow(value:Number):void 
		{
			_timeShow = value;
		}
		
		public function get borderWidth():Number { return _borderWidth; }
		
		public function set borderWidth(value:Number):void 
		{
			_borderWidth = value;
		}
		
		public function get borderColor():Number { return _borderColor; }
		
		public function set borderColor(value:Number):void 
		{
			_borderColor = value;
		}
		
		
		
		
	}
	
}